﻿using UnityEngine;
using System.Collections;

public class ChasingEnemy : MonoBehaviour {

    public Transform target;
    public float speed = 1;
    public float spotRange = 10;
    public float looseRange = 15;

    private bool isChasing = false;
    static private Vector3 rightTurn = new Vector3(0.0f, 0.0f, 0.0f);
    static private Vector3 leftTurn = new Vector3(0.0f, 180.0f, 0.0f);


	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {

        float distance = Vector3.Distance(transform.position, target.position);

        if (distance <= spotRange)
        {
            isChasing = true;
        }
        else if (distance > looseRange)
        {
            isChasing = false;
        }
        if (isChasing)
        {
            Vector3 previousPosition = new Vector3(transform.position.x, transform.position.y, transform.position.z);
            transform.LookAt(target);
            transform.Translate(Vector3.forward * speed * Time.deltaTime);

            if (previousPosition.x < transform.position.x)
            {
                transform.localEulerAngles = rightTurn;
            }
            else if (previousPosition.x > transform.position.x)
            {
                transform.localEulerAngles = leftTurn;
            }
        }

	}
}
